package manage.ship.service.impl;

import java.util.ArrayList;
import java.util.List;

import manage.ship.exception.SplitException;
import manage.ship.model.GoodModel;
import manage.ship.service.OperatorService;
import spring.module.Service;

@Service
public class OperatorServiceImpl implements OperatorService {
	/** 存储分配比例 **/
	private int[] rationArr = new int[] {2,3,5};

	public void initRatio(int... ration) {
		rationArr = ration;
	}

	public GoodModel split(int total) {
		int totalRation = getTotalRation();
		int assignedQuantity = 0;
		GoodModel goodModel = null;
		List<GoodModel> childGood = new ArrayList<>(rationArr.length);
		for (int i : rationArr) {
			goodModel = new GoodModel();
			goodModel.setCurrentQuantity(total * i / totalRation);
			childGood.add(goodModel);
			assignedQuantity += goodModel.getCurrentQuantity();
		}

		if (assignedQuantity != total) {
			throw new SplitException("split error,total is " + total + " assignedQuantity is " + assignedQuantity);
		}

		goodModel = new GoodModel();
		goodModel.setCurrentQuantity(total);

		goodModel.setChildGood(childGood.toArray(new GoodModel[childGood.size()]));
		return goodModel;
	}

	@Override
	public GoodModel merge(int total) {
		return split(total).sort();
	}

	private int getTotalRation() {
		int totalRation = 0;
		for (int i : rationArr) {
			totalRation += i;
		}
		return totalRation;
	}
}
